/*******************************************************************************
 * Package: com.hngtrust.iir.company.service.impl
 * Type:    ManageServiceImpl
 * Date:    2021-5-26 9:47
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.company.service.impl;

import com.hngtrust.framework.id.service.MyIdGenerator;
import com.hngtrust.framework.page.PageParam;
import com.hngtrust.framework.page.PageResult;
import com.hngtrust.framework.page.service.PageService;
import com.hngtrust.iir.base.entity.Dict;
import com.hngtrust.iir.base.service.DictService;
import com.hngtrust.iir.company.controller.vo.AiCompanyReqVO;
import com.hngtrust.iir.company.controller.vo.CompMainBusinessrReqVO;
import com.hngtrust.iir.company.controller.vo.CompMainbusinessRespVO;
import com.hngtrust.iir.company.controller.vo.CompStockRespVO;
import com.hngtrust.iir.company.controller.vo.ListAnnualRespVO;
import com.hngtrust.iir.company.controller.vo.ListBidReqVO;
import com.hngtrust.iir.company.controller.vo.ListBidRespVO;
import com.hngtrust.iir.company.controller.vo.ListCreditRateRespVO;
import com.hngtrust.iir.company.controller.vo.ListCustomerRespVO;
import com.hngtrust.iir.company.controller.vo.ListHolderReqVO;
import com.hngtrust.iir.company.controller.vo.ListQualificationRespVO;
import com.hngtrust.iir.company.controller.vo.ListSupplierRespVO;
import com.hngtrust.iir.company.controller.vo.ListTaxRespVO;
import com.hngtrust.iir.company.entity.CompAnnual;
import com.hngtrust.iir.company.entity.CompBid;
import com.hngtrust.iir.company.entity.CompCreditRate;
import com.hngtrust.iir.company.entity.CompCustomer;
import com.hngtrust.iir.company.entity.CompMainBusiness;
import com.hngtrust.iir.company.entity.CompProfit;
import com.hngtrust.iir.company.entity.CompQualification;
import com.hngtrust.iir.company.entity.CompStock;
import com.hngtrust.iir.company.entity.CompSupplier;
import com.hngtrust.iir.company.entity.CompTaxCredit;
import com.hngtrust.iir.company.service.CompAnnualService;
import com.hngtrust.iir.company.service.CompBidService;
import com.hngtrust.iir.company.service.CompCreditRateService;
import com.hngtrust.iir.company.service.CompCustomerService;
import com.hngtrust.iir.company.service.CompMainBusinessService;
import com.hngtrust.iir.company.service.CompProfitService;
import com.hngtrust.iir.company.service.CompQualificationService;
import com.hngtrust.iir.company.service.CompStockService;
import com.hngtrust.iir.company.service.CompSupplierService;
import com.hngtrust.iir.company.service.CompTaxCreditService;
import com.hngtrust.iir.company.service.ManageService;
import com.hngtrust.iir.constant.Constant;
import com.hngtrust.iir.dto.ReqDTO;
import com.hngtrust.iir.util.DateUtils;
import com.hngtrust.iir.util.ListUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 公司经营信息
 *
 * @author Chentianyong
 * @date 2021-5-26 9:47
 */
@Service
public class ManageServiceImpl implements ManageService {
    @Autowired
    private CompStockService compStockService;
    
    @Autowired
    private CompSupplierService compSupplierService;
    
    @Autowired
    private CompCustomerService compCustomerService;
    
    @Autowired
    private CompTaxCreditService compTaxCreditService;
    
    @Autowired
    private CompBidService compBidService;
    
    @Autowired
    private CompAnnualService compAnnualService;
    
    @Autowired
    private CompQualificationService compQualificationService;
    
    @Autowired
    private CompCreditRateService compCreditRateService;
    
    @Autowired
    private CompMainBusinessService compMainBusinessService;
    
    @Autowired
    private CompProfitService compProfitService;
    
    
    @Autowired
    private DictService dictService;
    
    /**
     * 分页服务
     */
    @Autowired
    private PageService pageService;
    
    /**
     * 主键生成器
     */
    @Autowired
    private MyIdGenerator myIdGenerator;
    
    @Override
    public CompStockRespVO infoStock(ListHolderReqVO req) {
        CompStock compStock = new CompStock();
        BeanUtils.copyProperties(req,compStock);
        compStock.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        compStock = compStockService.queryStock(req.getCompId());
        CompStockRespVO resp = new CompStockRespVO();
        if(null != compStock){
            BeanUtils.copyProperties(compStock,resp);
        
            //当前价
            resp.setPCurrent(resp.getPreClose().add(resp.getPChange()));
        }
        else{
            resp = null;
        }
        
        return resp;
    }
    
    @Override
    public CompMainbusinessRespVO compMainbusiness(CompMainBusinessrReqVO req) {
        CompMainbusinessRespVO resp = new CompMainbusinessRespVO();
        CompMainBusiness mb = new CompMainBusiness();
        BeanUtils.copyProperties(req,mb);
        List<CompMainBusiness> list = compMainBusinessService.queryMBGroupYear(mb);
        if(list.isEmpty()){
            return null;
        }
        Date maxDate = list.get(0).getReportPeriod();
    
        if(req.getYearType().equals(Constant.MAIN_YEAR_TYPE_ALL)){
            Date minDate = list.get(list.size() - 1).getReportPeriod();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(minDate);
            minDate = DateUtils.getDate(String.valueOf(calendar.get(Calendar.YEAR))+"-01-01");
            mb.setReportPeriod(minDate);
            list = compMainBusinessService.queryMBGroup(mb);
        }
        else if(req.getYearType().equals(Constant.MAIN_YEAR_TYPE_HALF)){
            list = compMainBusinessService.queryMBGroupHalfYear(mb);
        }
        if(list.isEmpty()){
            return resp;
        }
    
        
        resp.setCompId(req.getCompId());
        List<CompMainbusinessRespVO.MainBusiness> mainBusinessList = new ArrayList<>();
    
        //利润表的营业收入
        CompProfit compProfit = new CompProfit();
        compProfit.setCompId(req.getCompId());
        compProfit.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        List<CompProfit> profitList = compProfitService.queryYearHalfReport(compProfit);
        Calendar calendar = Calendar.getInstance();
        for(CompMainBusiness mbData : list){
            CompMainbusinessRespVO.MainBusiness mainBusiness = new CompMainbusinessRespVO.MainBusiness();
            mainBusiness.setReportPeriod(mbData.getReportPeriod());
            mainBusiness.setSegmentSales(mbData.getSegmentSales());
        
            //主营业务收入比上年增减(%)
            calendar.setTime(mbData.getReportPeriod());
            int preYear = calendar.get(Calendar.YEAR) - 1;
            int month = calendar.get(Calendar.MONTH);
            CompMainBusiness preData = null;
            for(CompMainBusiness obj : list){
                calendar.setTime(obj.getReportPeriod());
                if(calendar.get(Calendar.YEAR) == preYear && calendar.get(Calendar.MONDAY) == month){
                    preData = obj;
                    break;
                }
            }
            if(null != preData && null != mbData.getSegmentSales() && null != preData.getSegmentSales()){
                mainBusiness.setPrimeOperRevYoy((mbData.getSegmentSales().subtract(preData.getSegmentSales())).divide(preData.getSegmentSales(),Constant.RETAIN_DECIMAL_DIGIT_SIX,
                        RoundingMode.HALF_UP).multiply(
                        BigDecimal.valueOf(100)).setScale(2,RoundingMode.HALF_UP));
            }
            //主营业务收入比例(%)
            CompProfit curProfit = null;
            for(CompProfit profit : profitList){
                if(mbData.getReportPeriod().equals(profit.getReportPeriod())){
                    curProfit = profit;
                    break;
                }
            }
            if(null != curProfit && null != mbData.getSegmentSales() && null != curProfit.getTotOperRev()){
                mainBusiness.setSegmentSaleRatio(mbData.getSegmentSales().divide(curProfit.getTotOperRev(),Constant.RETAIN_DECIMAL_DIGIT_SIX,
                        RoundingMode.HALF_UP).multiply(
                        BigDecimal.valueOf(100)).setScale(2,RoundingMode.HALF_UP));
                if(mainBusiness.getSegmentSaleRatio().compareTo(BigDecimal.valueOf(100)) > 0){
                    mainBusiness.setSegmentSaleRatio(BigDecimal.valueOf(100));
                }
            }
        
            mainBusinessList.add(mainBusiness);
        }
        //处理最近5年
        Boolean year1 = false;
        Boolean year2 = false;
        Boolean year3 = false;
        Boolean year4 = false;
        Boolean year5 = false;
        for(CompMainbusinessRespVO.MainBusiness obj : mainBusinessList){
            if(DateUtils.getYear(obj.getReportPeriod()) == DateUtils.getYear(new Date()) - 1){
                year1 = true;
            }
            if(DateUtils.getYear(obj.getReportPeriod()) == DateUtils.getYear(new Date()) - 2){
                year2 = true;
            }
            if(DateUtils.getYear(obj.getReportPeriod()) == DateUtils.getYear(new Date()) - 3){
                year3 = true;
            }
            if(DateUtils.getYear(obj.getReportPeriod()) == DateUtils.getYear(new Date()) - 4){
                year4 = true;
            }
            if(DateUtils.getYear(obj.getReportPeriod()) == DateUtils.getYear(new Date()) - 5){
                year5 = true;
            }
        }
        String yearStr = "-12-31";
        if(req.getYearType().equals(Constant.MAIN_YEAR_TYPE_HALF)){
            yearStr = "-06-30";
        }
        if(!year1){
            CompMainbusinessRespVO.MainBusiness mbData = new CompMainbusinessRespVO.MainBusiness();
            mbData.setReportPeriod(DateUtils.getDate(String.valueOf(DateUtils.getYear(new Date()) - 1) + yearStr));
            mainBusinessList.add(0,mbData);
        }
        if(!year2){
            CompMainbusinessRespVO.MainBusiness mbData = new CompMainbusinessRespVO.MainBusiness();
            mbData.setReportPeriod(DateUtils.getDate(String.valueOf(DateUtils.getYear(new Date()) - 2) + yearStr));
            mainBusinessList.add(1,mbData);
        }
        if(!year3){
            CompMainbusinessRespVO.MainBusiness mbData = new CompMainbusinessRespVO.MainBusiness();
            mbData.setReportPeriod(DateUtils.getDate(String.valueOf(DateUtils.getYear(new Date()) - 3) + yearStr));
            mainBusinessList.add(2,mbData);
        }
        if(!year4){
            CompMainbusinessRespVO.MainBusiness mbData = new CompMainbusinessRespVO.MainBusiness();
            mbData.setReportPeriod(DateUtils.getDate(String.valueOf(DateUtils.getYear(new Date()) - 4) + yearStr));
            mainBusinessList.add(3,mbData);
        }
        if(!year5){
            CompMainbusinessRespVO.MainBusiness mbData = new CompMainbusinessRespVO.MainBusiness();
            mbData.setReportPeriod(DateUtils.getDate(String.valueOf(DateUtils.getYear(new Date()) - 5) + yearStr));
            mainBusinessList.add(4,mbData);
        }
    
        resp.setMainBusiness(mainBusinessList);
    
        //营收种类
        mb.setReportPeriod(maxDate);
        PageParam page = new PageParam();
        page.setPageNum(1);
        page.setPageSize(0);
        page.setOrderBy("segment_sale_ratio desc");
        PageResult<CompMainBusiness> pageList = pageService.page(page, () -> compMainBusinessService.queryList(mb));
    
        list = pageList.getRows();//compMainBusinessService.queryList(mb);
        List<CompMainbusinessRespVO.BusinessType> businessTypeList = new ArrayList<>();
        ListUtil<CompMainbusinessRespVO.BusinessType> listUtil2 = BeanUtils.instantiateClass(ListUtil.class);
        listUtil2.copyList(list,businessTypeList, CompMainbusinessRespVO.BusinessType.class);
        resp.setBusinessType(businessTypeList);
        resp.setReportPeriod(maxDate);
    
        return resp;
    }
    
    @Override
    public PageResult<ListSupplierRespVO> listSupplier(ReqDTO<ListHolderReqVO> req) {
        CompSupplier compSupplier = new CompSupplier();
        BeanUtils.copyProperties(req.getContent(),compSupplier);
        compSupplier.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        PageResult<CompSupplier> page = pageService.page(req.getPageParam(), () -> compSupplierService.queryList(compSupplier));
    
        PageResult<ListSupplierRespVO> pageResult = new PageResult<>();
        ListUtil<ListSupplierRespVO> listUtil = BeanUtils.instantiateClass(ListUtil.class);
        listUtil.copyList(page,pageResult,ListSupplierRespVO.class);
        
        return pageResult;
    }
    
    @Override
    public PageResult<ListCustomerRespVO> listCustomer(ReqDTO<ListHolderReqVO> req) {
        CompCustomer compCustomer = new CompCustomer();
        BeanUtils.copyProperties(req.getContent(),compCustomer);
        compCustomer.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        PageResult<CompCustomer> page = pageService.page(req.getPageParam(), () -> compCustomerService.queryList(compCustomer));
    
        PageResult<ListCustomerRespVO> pageResult = new PageResult<>();
        ListUtil<ListCustomerRespVO> listUtil = BeanUtils.instantiateClass(ListUtil.class);
        listUtil.copyList(page,pageResult,ListCustomerRespVO.class);
        
        return pageResult;
    }
    
    @Override
    public List<AiCompanyReqVO> listBidType() {
        List<CompBid> list = compBidService.listType();
    
        List<AiCompanyReqVO> resp = new ArrayList<>();
        for(CompBid bid : list){
            AiCompanyReqVO obj = new AiCompanyReqVO();
            obj.setName(bid.getInfoType());
            resp.add(obj);
        }
        
        return resp;
    }
    
    @Override
    public PageResult<ListBidRespVO> listBid(ReqDTO<ListBidReqVO> req) {
        CompBid bid = new CompBid();
        BeanUtils.copyProperties(req.getContent(),bid);
        bid.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        if(null != req.getContent().getReleaseDate() && !req.getContent().getReleaseDate().isEmpty()){
            bid.setReleaseDate(DateUtils.getDate(req.getContent().getReleaseDate()+"-01-01"));
        }
        PageResult<CompBid> page = pageService.page(req.getPageParam(), () -> compBidService.queryBid(bid));
    
        PageResult<ListBidRespVO> pageResult = new PageResult<>();
        ListUtil<ListBidRespVO> listUtil = BeanUtils.instantiateClass(ListUtil.class);
        listUtil.copyList(page,pageResult,ListBidRespVO.class);
    
        //查询所有关联的公司
//        if(null != page.getRows() && !page.getRows().isEmpty()){
//            List<Long> bidIds = page.getRows().stream().map(u->u.getId()).collect(Collectors.toList());
//            List<CompBidRel> compBidRelList = compBidRelService.queryByBidIds(bidIds);
//
//            for(ListBidRespVO compBid : pageResult.getRows()) {
//                List<ListBidRespVO.RelComp> bidList = new ArrayList<>();
//                List<ListBidRespVO.RelComp> candiList = new ArrayList<>();
//                List<ListBidRespVO.RelComp> relList = new ArrayList<>();
//                for(CompBidRel compRel : compBidRelList){
//                    if(compBid.getId().equals(compRel.getBidId())){
//                        ListBidRespVO.RelComp obj = new ListBidRespVO.RelComp();
//                        BeanUtils.copyProperties(compRel, obj);
//                        if (compRel.getRelType().equals(Constant.BID_REL_TYPE_BID)) {
//                            bidList.add(obj);
//                        }
//                        else if (compRel.getRelType().equals(Constant.BID_REL_TYPE_CANDI)) {
//                            candiList.add(obj);
//                        }
//                        else if (compRel.getRelType().equals(Constant.BID_REL_TYPE_REL)) {
//                            relList.add(obj);
//                        }
//                    }
//
//                }
//                compBid.setBidComps(bidList);
//                compBid.setCandiComps(candiList);
//                compBid.setRelComps(relList);
//            }
//        }
    
        return pageResult;
    }
    
    @Override
    public PageResult<ListTaxRespVO> listTax(ReqDTO<ListHolderReqVO> req) {
        CompTaxCredit compTax = new CompTaxCredit();
        BeanUtils.copyProperties(req.getContent(),compTax);
        compTax.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        PageResult<CompTaxCredit> page = pageService.page(req.getPageParam(), () -> compTaxCreditService.queryList(compTax));
    
        PageResult<ListTaxRespVO> pageResult = new PageResult<>();
        ListUtil<ListTaxRespVO> listUtil = BeanUtils.instantiateClass(ListUtil.class);
        listUtil.copyList(page,pageResult,ListTaxRespVO.class);
        
        return pageResult;
    }
    
    @Override
    public PageResult<ListCreditRateRespVO> listCreditRate(ReqDTO<ListHolderReqVO> req) {
        CompCreditRate compCreditRate = new CompCreditRate();
        BeanUtils.copyProperties(req.getContent(),compCreditRate);
        compCreditRate.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        PageResult<CompCreditRate> page = pageService.page(req.getPageParam(), () -> compCreditRateService.queryList(compCreditRate));
    
        PageResult<ListCreditRateRespVO> pageResult = new PageResult<>();
        ListUtil<ListCreditRateRespVO> listUtil = BeanUtils.instantiateClass(ListUtil.class);
        listUtil.copyList(page,pageResult,ListCreditRateRespVO.class);
    
        //处理数据字典值
        List<ListCreditRateRespVO> voList = new ArrayList<>();
        Map<String, Dict> dictStyle = dictService.queryDict("RATE_STYLE");
        Map<String, Dict> dictOutlook = dictService.queryDict("RATE_OUTLOOK");
        Map<String, Dict> dictInfo = dictService.queryDict("INFO_CREDITRATINGAGENCY");
        for(ListCreditRateRespVO obj:pageResult.getRows()){
            if(null != obj.getRateStyle() && null != dictStyle && null != dictStyle.get(obj.getRateStyle().toString())){
                obj.setRateStyleName(dictStyle.get(obj.getRateStyle().toString()).getBusiName());
            }
            if(null != obj.getRateOutlook() && null != dictOutlook && null != dictStyle.get(obj.getRateOutlook().toString())){
                obj.setRateOutlookName(dictStyle.get(obj.getRateOutlook().toString()).getBusiName());
            }
            if(null != obj.getCreditAgency() && !obj.getCreditAgency().isEmpty() && null != dictInfo && null != dictInfo.get(obj.getCreditAgency())){
                obj.setCreditAgencyName(dictInfo.get(obj.getCreditAgency()).getBusiName());
            }
            voList.add(obj);
        }
        pageResult.setRows(voList);
    
        return pageResult;
    }
    
    @Override
    public PageResult<ListAnnualRespVO> listAnnual(ReqDTO<ListHolderReqVO> req) {
        CompAnnual compAnnual = new CompAnnual();
        BeanUtils.copyProperties(req.getContent(),compAnnual);
        compAnnual.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        PageResult<CompAnnual> page = pageService.page(req.getPageParam(), () -> compAnnualService.queryList(compAnnual));
    
        PageResult<ListAnnualRespVO> pageResult = new PageResult<>();
        ListUtil<ListAnnualRespVO> listUtil = BeanUtils.instantiateClass(ListUtil.class);
        listUtil.copyList(page,pageResult,ListAnnualRespVO.class);
        
        return pageResult;
    }
    
    @Override
    public PageResult<ListQualificationRespVO> listQualification(ReqDTO<ListHolderReqVO> req) {
        CompQualification compQualification = new CompQualification();
        BeanUtils.copyProperties(req.getContent(),compQualification);
        compQualification.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        PageResult<CompQualification> page = pageService.page(req.getPageParam(), () -> compQualificationService.queryQualification(compQualification));
    
        PageResult<ListQualificationRespVO> pageResult = new PageResult<>();
        pageResult.setPage(page.getPage());
    
        //处理数据
        List<ListQualificationRespVO> voList = new ArrayList<>();
        for(CompQualification cq:page.getRows()){
            ListQualificationRespVO obj = new ListQualificationRespVO();
            BeanUtils.copyProperties(cq,obj);
            obj.setValid("是");
            if(null != cq.getRevokeDate() && !cq.getRevokeDate().toString().isEmpty()){
                obj.setValid("否");
            }
            voList.add(obj);
        }
        pageResult.setRows(voList);
    
        return pageResult;
    }
}
